<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/js/include.js"></script>
    <script src="/js/rsaEncrypt.js"></script>
</head>
<body>
    <div id="app">
        <div >
            <table>
                <tr>
                    <td>
                        <el-input v-model="searchForm.nickName" placeholder="昵称模糊搜索" clearable style="width: 200px;"></el-input>
                    </td>
                    <td>
                        <el-select v-model="searchForm.status" clearable placeholder="状态">
                            <el-option
                                    v-for="item in statuses"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </td>
                    <td>
                        <treeselect v-model="searchForm.departmentId" :options="departmentTree" placeholder="所属部门" style="width: 200px;"/>
                    </td>
                    <td>
                        <button @click="search" type="button" class="el-button filter-item el-button--success el-button--small">
                            <i class="el-icon-search"></i><span>搜索</span>
                        </button>
                    </td>
                    <td>
                        <button @click="toAdd" v-if="showButtonAdd" type="button" class="el-button el-button--primary el-button--small">
                            <i class="el-icon-plus"></i><span>新增</span>
                        </button>
                    </td>
                </tr>
            </table>
        </div>

        <div style="margin-top: 5px;">
            <el-table
                    :data="pg.list"
                    style="width: 100%;margin-bottom: 20px;"
                    v-loading="loading">
                </el-table-column>
                <el-table-column
                        prop="nickName"
                        label="昵称">
                </el-table-column>
                <el-table-column
                        label="所属部门">
                    <template slot-scope="scope">
                        {{getDepartmentName(scope.row.departmentId)}}
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <span v-if="scope.row.status" class="el-tag el-tag--success el-tag--small el-tag--light">启用</span>
                        <span v-else class="el-tag el-tag--warning el-tag--small el-tag--light">禁用</span>
                    </template>
                </el-table-column>
                <el-table-column
                        label="创建时间">
                    <template slot-scope="scope">
                        {{scope.row.createdTime | dateTimeFormat('yyyy-MM-dd HH:mm:ss')}}
                    </template>
                </el-table-column>

                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="showButtonUpdate" @click="toModify(scope.row)" type="primary" icon="el-icon-edit" size="mini" title="修改"></el-button>
                        <template v-if="scope.row.children == null" >
                            <el-button v-if="showButtonDelete" type="danger" icon="el-icon-delete" size="mini" title="删除" @click="del(scope.row.id)"></el-button>
                        </template>
                    </template>

                </el-table-column>

            </el-table>
        </div>

        <my-el-pagination :total="pg.total" @pagination_change="pagination_change" :page_index="pg.pageNum"></my-el-pagination>

        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                :close-on-click-modal="false"
                :loading="loading"
                width="50%">

            <el-form :inline="true" :model="editForm" ref="editForm" :rules="rules" label-width="100px" class="demo-form-inline">
                <el-form-item label="用户名" prop="loginName">
                    <el-input v-model="editForm.loginName" :disabled="editForm.id !== undefined && editForm.id !== '' && editForm.id !== null" style="width: 200px"></el-input>
                </el-form-item>

                <el-form-item label="电话" prop="phone">
                    <el-input v-model="editForm.phone" style="width: 200px"></el-input>
                </el-form-item>

                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="editForm.nickName" style="width: 200px"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" style="width: 200px"></el-input>
                </el-form-item>

                <el-form-item label="职位" prop="positionId" >
                    <el-select v-model="editForm.positionId" filterable placeholder="请选择" style="width: 200px">
                        <el-option
                                v-for="item in positions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="角色" prop="checkedRoleIds">
                    <el-select v-model="checkedRoleIds" multiple filterable placeholder="请选择" style="width: 200px">
                        <el-option
                                v-for="item in roles"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="所属部门" prop="departmentId">
                    <treeselect v-model="editForm.departmentId" :options="departmentTree" style="width: 200px" placeholder="所属部门"/>
                </el-form-item>

                <el-form-item label="性别" prop="gender">
                    <el-radio v-for="item in genders" v-model="editForm.gender" :label="item.value">{{item.label}}</el-radio>
                </el-form-item>

                <el-form-item label="数据范围" prop="dataScope">
                    <el-select v-model="editForm.dataScope" placeholder="请选择" style="width: 200px">
                        <el-option
                                v-for="item in dataScopes"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-radio v-for="item in statuses" v-model="editForm.status" :label="item.value">{{item.label}}</el-radio>
                </el-form-item>

                <el-form-item v-if="editForm.dataScope === dataScopesJson.CUSTOMIZED.value" label="数据范围">
                    <treeselect v-model="checkedDataScope" :options="departmentTree" :multiple="true" :flat="true" style="width: 500px" placeholder="数据范围"/>
                </el-form-item>

                <el-form-item label="独立权限">
                    <treeselect v-model="checkedMenuIds" :options="menuTree" :multiple="true" :flat="true" style="width: 500px" placeholder="独立权限"/>
                </el-form-item>

            </el-form>


            <span slot="footer" class="dialog-footer">
                &nbsp;<el-button type="primary" @click="submitForm">确 定</el-button>
                &nbsp;<el-button @click="dialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>

    </div>
</body>
<script>
    Vue.component('treeselect', VueTreeselect.Treeselect);

    let dataScopeEnum = MY_ENUM.getElOptions("DataScope").sort(COMPARE_ASC("value"));
    let switchEnum = MY_ENUM.getElOptions("Switch").sort(COMPARE_DESC("value"));
    let genderEnum = MY_ENUM.getElOptions("Gender").sort(COMPARE_DESC("value"));

    let vm = new Vue({
        el: '#app',
        data: {
            pg: {
                totalCount: 0,
                data: []
            },
            tableData: [],
            searchForm: {
                currentPage: 1,
                pageSize: DEFAULT_PAGE_SIZE,
                departmentId: null,
                status: null
            },
            dialogVisible: false,
            dialogTitle: "",
            editForm: {

            },
            rules: {
                loginName: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
                nickName: [{ required: true, trigger: 'blur', message: '请输入昵称' }],
                phone: [{ required: true, trigger: 'blur', message: '请输入电话' }],
                gender: [{ required: true, trigger: 'blur', message: '请选择性别' }],
                email: [{ required: true, trigger: 'blur', message: '请输入邮箱' }],
                positionId: [{ required: true, trigger: 'blur', message: '请选择职位' }],
                departmentId: [{ required: true, trigger: 'blur', message: '请选择部门' }],
                dataScope: [{ required: true, trigger: 'blur', message: '请选择数据范围' }],
            },
            loading: false,
            statuses: switchEnum,
            genders: genderEnum,
            dataScopes: dataScopeEnum,
            dataScopesJson: MY_ENUM.getEnum("DataScope"),
            departmentTree: [],
            departments: [],
            positions: [],
            menus: [],
            menuTree: [],
            roles: [],
            checkedDataScope: [], // 选中数据范围
            checkedRoleIds: [],    // 选中的角色,
            checkedMenuIds: [], // 选中独立权限
        },
        methods: {
            pagination_change (item) {
                this.searchForm.pageNum = item.pageNum;
                this.searchForm.pageSize = item.pageSize;
                this.loadTableData();
            },
            submitForm() {
                let that = this;
                this.$refs["editForm"].validate((valid) => {
                    if (!valid) {
                        return false;
                    }

                    if (that.checkedRoleIds.length < 1) {
                        warningMessage("请选中角色！");
                        return;
                    }

                    myConfirm("确定提交？", function () {
                        showLoading("保存中....");
                        let url = BASE_PATH + "/user/update";
                        if (isEmpty(that.editForm.id)) {
                            url = BASE_PATH + "/user/add";
                        }

                        Vue.delete(that.editForm, "createdTime");
                        let userVo = packInfo(that);

                        myAjax({
                            type: "post",
                            url: url,
                            data: userVo,
                            isJson: true,
                            callback: function () {
                                hideLoading();
                                successMessage("提交成功！");
                                that.dialogVisible = false;
                                that.loadTableData();
                            }
                        })
                    });
                });
            },
            search() {
                this.searchForm.pageNum = 1;
                this.loadTableData();
            },
            loadTableData(){
                let that = this;
                this.loading = true;
                myAjax({
                    type: "get",
                    url: BASE_PATH + "/user/list",
                    data: that.searchForm,
                    callback: function (data) {
                        that.pg = data;
                        that.loading = false;
                    }
                });
            },
            toModify(obj){
                this.dialogTitle = "编辑用户";
                this.dialogVisible = true;
                this.loading = true;
                let that = this;
                this.editForm = JSON.parse(JSON.stringify(obj));
                myAjax({
                    type: "get",
                    url: BASE_PATH + "/user/detail",
                    data:{id: obj.id},
                    callback: function (data) {
                        let roleIds = [];
                        for (let i = 0; i < data.userRoles.length; i++) {
                            roleIds.push(data.userRoles[i].roleId);
                        }
                        that.checkedRoleIds = roleIds;

                        if (obj.dataScope === that.dataScopesJson.CUSTOMIZED.value) {
                            let departmentIds = [];
                            for (let i = 0; i < data.userDataScopes.length; i++) {
                                departmentIds.push(data.userDataScopes[i].departmentId);
                            }
                            that.checkedDataScope = departmentIds;
                        }

                        if (data.userMenus != null) {
                            let menuIds = [];
                            for (let i = 0; i < data.userMenus.length; i++) {
                                menuIds.push(data.userMenus[i].menuId);
                            }
                            that.checkedMenuIds = menuIds;
                        }

                        that.loading = false;
                    }
                });


            },
            toAdd(obj){
                this.dialogTitle = "新增用户";
                this.editForm = {
                    id: "",
                    status: this.statuses[0].value,
                    gender: this.genders[0].value
                };
                this.checkedRoleIds = [];
                this.checkedDataScope = [];
                this.checkedMenuIds = [];
                this.dialogVisible = true;
            },
            del(id) {
                let that = this;
                myConfirm("确定删除？", function () {
                    showLoading("保存中....");
                    let settings = {
                        type: "post",
                        url: BASE_PATH + "/user/delete",
                        data: {id : id},
                        callback: function () {
                            hideLoading();
                            successMessage("删除成功！");
                            that.loadTableData();
                        }
                    };
                    myAjax(settings);
                });

            },

            getDepartmentName(val) {
                for (let i = 0; i < this.departments.length; i++) {
                    if (this.departments[i].id === val) {
                        return this.departments[i].name;
                    }
                }
            },
        },
        created:function () {
            this.loadTableData();
            loadDepartmentTree();
            loadRoles();
            loadPositions();
            loadMenus();
            this.showButtonAdd = parent.checkPermissionByName("用户添加");
            this.showButtonUpdate = parent.checkPermissionByName("用户修改");
            this.showButtonDelete = parent.checkPermissionByName("用户删除");
        },
    });

    /**
     * 包装提交的数据
     * @param that vue对象
     */
    function packInfo(that) {
        let userVo = {};
        userVo.user = JSON.parse(JSON.stringify(that.editForm));

        // 多选的角色
        let userRoles = [];
        for (let i = 0; i < that.checkedRoleIds.length; i++) {
            let userRole = {
                roleId: that.checkedRoleIds[i]
            };
            userRoles.push(userRole);
        }
        userVo.userRoles = userRoles;

        // 多选的数据范围
        if (that.editForm.dataScope === that.dataScopesJson.CUSTOMIZED.value) {
            let userDataScopes = [];
            for (let i = 0; i < that.checkedDataScope.length; i++) {
                let userDataScope = {
                    departmentId: that.checkedDataScope[i]
                };
                userDataScopes.push(userDataScope);
            }
            userVo.userDataScopes = userDataScopes;
        }

        // 独立权限
        if (that.checkedMenuIds.length > 0) {
            let userMenus = [];
            for (let i = 0; i < that.checkedMenuIds.length; i++) {
                let userMenu = {
                    menuId: that.checkedMenuIds[i]
                };
                userMenus.push(userMenu);
            }
            userVo.userMenus = userMenus;
        }
        return userVo;
    }
    function loadDepartmentTree() {
        myAjax({
            type: "get",
            url: BASE_PATH + "/sys/departmentList",
            callback: function (data) {
                vm.departments = JSON.parse(JSON.stringify(data));;
                // 添加label属性 把name值赋给他
                for (let i = 0; i < data.length; i++) {
                    data[i].label = data[i].name;
                }
                vm.departmentTree = toTree(data);
            }
        });
    }
    function loadRoles(){
        myAjax({
            type: "get",
            url: BASE_PATH + "/sys/roleList",
            callback: function (data) {
                vm.roles = data;
            }
        });
    }
    function loadPositions() {
        myAjax({
            type: "get",
            url: BASE_PATH + "/sys/positionList",
            callback: function (data) {
                vm.positions = data;
            }
        });
    }
    function loadMenus() {
        myAjax({
            type: "get",
            url: BASE_PATH + "/sys/menuList",
            callback: function (data) {
                vm.menus = JSON.parse(JSON.stringify(data));
                // 添加label属性 把name值赋给它。
                for (let i = 0; i < data.length; i++) {
                    data[i].label = data[i].name;
                }
                vm.menuTree = toTree(data);
            }
        });

    }
</script>
</html>
